<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/bootstrap.min.css">
    <script src="./js/jquery.min.js"></script>
</head>
<body>
    <input type="file" name="" id="file">
    <button id="btnUpload">上传</button>
    <!-- 进度条 -->
    <div class="progress" style="margin: 15px; width: 300px; margin-left: 0;">
        <div class="progress-bar progress-bar-striped active" style="width: 0%" id="mybar">
            0%
        </div>
        0%
    </div>
    <!-- <br> -->
    <img src="" alt="" id="img" width="100">
    <script>
        
        var btn = document.querySelector('#btnUpload');
        btn.addEventListener('click',function(){
            var file = document.querySelector('#file').files;
            if(file.length <= 0) {
                return alert('请上传文件');
            }else{
                var fd = new FormData();
                fd.append('avatar',file[0]);
                var xhr = new XMLHttpRequest();
                var mybar = document.querySelector('#mybar');
                var p = 0;
                xhr.upload.onprogress = function(e) {
                    if (e.lengthComputable) {
                        var procentComputable = Math.ceil((e.loaded/e.total) * 100);
                        p = procentComputable;
                        mybar.style.width = procentComputable + '%';
                        mybar.innerHTML = procentComputable + '%';
                    }
                }
                xhr.upload.onloadend = function(){
                    mybar.classList.add('progress-bar-success');
                    mybar.innerHTML = p + '%';
                }
                xhr.open('post','http://www.liulongbin.top:3006/api/upload/avatar');
                xhr.send(fd);
                xhr.onreadystatechange = function(){
                    if (this.readyState === 4 && this.status === 200) {
                        var data = JSON.parse(this.responseText);
                        console.log(data);
                        if (data.status === 200) {//上传成功
                            document.querySelector('#img').src = 'http://www.liulongbin.top:3006' + data.url;
                        }else{
                            console.log(data.message);
                        }
                    }
                }
            }
        })

    </script>
</body>
</html>